package sample.tomcat;

import org.apache.catalina.LifecycleException;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.loader.WebappLoader;
import org.apache.catalina.startup.Tomcat;
import org.springframework.boot.web.embedded.tomcat.TomcatEmbeddedWebappClassLoader;
import org.springframework.boot.web.embedded.tomcat.TomcatWebServer;

import java.io.File;
import java.util.Collections;

/**
 * 手动启动tomcat
 *
 * @author zhouzx
 */
public class MyOwnTomcatApplication {
    public static void main(String[] args) throws InterruptedException, LifecycleException {
        Tomcat tomcat = new Tomcat();
        File baseDir = new File("c:/tmp/tomcat");
        tomcat.setBaseDir(baseDir.getAbsolutePath());
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setPort(9090);
        tomcat.getService().addConnector(connector);
        tomcat.setConnector(connector);
        tomcat.getHost().setAutoDeploy(false);

        StandardContext context = new StandardContext();
        context.setName("/aa");
        context.setDisplayName("/aa");
        context.setPath("/aa");
        File docBase = new File("c:/tmp/tomcat-docbase");
        context.setDocBase(docBase.getAbsolutePath());
        context.addLifecycleListener(new Tomcat.FixContextListener());
        context.setUseRelativeRedirects(false);
        context.addServletContainerInitializer(new MyServletContainerInitializer(), Collections.emptySet());
        WebappLoader loader = new WebappLoader(context.getParentClassLoader());
        loader.setLoaderClass(TomcatEmbeddedWebappClassLoader.class.getName());
        loader.setDelegate(true);
        context.setLoader(loader);
        tomcat.getHost().addChild(context);

        TomcatWebServer tomcatWebServer = new TomcatWebServer(tomcat, true);

        //模拟出错，程序一直运行，未关闭，TomcatWebServer的构造方法中有Tomcat的start方法
        int i = 1 / 0;
    }
}
